package com.zy.fee.roadpark.activity.np;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.flyco.roundview.RoundLinearLayout;
import com.flyco.roundview.RoundTextView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.CommonLogic;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.config.LibraryConstants;
import com.zygk.library.model.CommonResult;
import com.zygk.library.util.ColorUtil;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ImageUtil;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.UUID;

/**
 * Created by Wikison on 2018/9/17.
 * 取证
 */
public class NpForensicsActivity extends BaseActivity {
  public static final String INTENT_PLATE_NUMBER = "INTENT_PLATE_NUMBER";
  public static final String INTENT_CODE = "INTENT_CODE";
  public static final String INTENT_NODE_RECORD_ID = "INTENT_NODE_RECORD_ID";

  @BindView(R.id.ll_back) LinearLayout llBack;
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.rll_code) RoundLinearLayout rllCode;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.iv_photo) ImageView ivPhoto;
  @BindView(R.id.ll_scan) LinearLayout llScan;
  @BindView(R.id.tv_button) RoundTextView tvButton;

  private ArrayList<ImageItem> images = null;
  private String carPath = "";
  private String plateNumber = "", code="", pic = "";
  private String nodeRecordID = "";

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_np_forensics);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    initImagePickerSingle(false);

    plateNumber = getIntent().getStringExtra(INTENT_PLATE_NUMBER);
    code = getIntent().getStringExtra(INTENT_CODE);
    nodeRecordID = getIntent().getStringExtra(INTENT_NODE_RECORD_ID);
  }

  private void initView() {
    lhTvTitle.setText("取证");
    llBack.setVisibility(View.GONE);

    gpvPlateNumber.setPassword(plateNumber);
    gpvPlateNumber.setEnabled(false);
    gpvPlateNumber.setFocusable(false);
    gpvPlateNumber.setClickable(false);
    gpvPlateNumber.togglePasswordVisibility();

    if(StringUtils.isBlank(code)){
      rllCode.setVisibility(View.GONE);
    }else {
      rllCode.setVisibility(View.VISIBLE);
      etCode.setText(code);
      etCode.setEnabled(false);
    }
  }

  private void initListener() {
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        String originImage = images.get(0).path;

        FileInputStream fis = null;
        try {
          fis = new FileInputStream(originImage);
          Bitmap bitmap = BitmapFactory.decodeStream(fis);

          if (null == bitmap) {
          } else {
            if (addWatermarkBitmap(bitmap, DateTimeUtil.getCurrentTime(), bitmap.getWidth(),
                bitmap.getHeight())) {
            } else {
              ToastUtil.showMessage(mContext, "水印添加失败");
              carPath = originImage;
            }
          }
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }

        llScan.setVisibility(View.GONE);
        ivPhoto.setVisibility(View.VISIBLE);
        tvButton.getDelegate()
            .setBackgroundColor(ColorUtil.getColor(mContext, R.color.theme_color));
      }
    }
  }

  private boolean addWatermarkBitmap(Bitmap bitmap, String strMark, int w, int h) {
    int destWidth = w;   //此处的bitmap已经限定好宽高
    int destHeight = h;

    Bitmap carBitmap =
        Bitmap.createBitmap(destWidth, destHeight, Bitmap.Config.ARGB_8888); //定好宽高的全彩bitmap
    Canvas canvas = new Canvas(carBitmap);//初始化画布绘制的图像到icon上

    Paint photoPaint = new Paint(); //建立画笔
    photoPaint.setDither(true); //获取跟清晰的图像采样
    photoPaint.setFilterBitmap(true);//过滤一些

    Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());//创建一个指定的新矩形的坐标
    Rect dst = new Rect(0, 0, destWidth, destHeight);//创建一个指定的新矩形的坐标
    canvas.drawBitmap(bitmap, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

    Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
    textPaint.setTextSize(destWidth / 20);//字体大小
    textPaint.setTextAlign(Paint.Align.CENTER);
    textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
    textPaint.setAntiAlias(true);  //抗锯齿
    textPaint.setStrokeWidth(3);
    textPaint.setAlpha(15);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(Color.RED);//水印文字颜色
    textPaint.setShadowLayer(1f, 0f, 3f, Color.LTGRAY);
    canvas.drawText(strMark, destWidth / 3, 100, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
    canvas.save();
    canvas.restore();
    bitmap.recycle();

    carPath = LibraryConstants.SAVE_IMAGE_PATH_IMGS + DateTimeUtil.getCurrentTime() + ".jpg";
    imageManager.loadLocalImage(carPath, ivPhoto);

    try {
      ImageUtil.saveImage(carBitmap, carPath);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  private void uploadPic() {
    String fileName = UUID.randomUUID().toString() + carPath.substring(carPath.lastIndexOf("."));

    CommonLogic.do_upload_pic(mContext, true, carPath, fileName, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        CommonResult result = (CommonResult) obj;
        pic = result.getData();
        updateNodeRecordPic();
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  private void updateNodeRecordPic() {
    NpNodeRecordLogic.uploadNodePic(mContext, nodeRecordID, pic, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showNoCancelPd();
      }

      @Override public void onSucceed(Object obj) {
        ToastUtil.showMessage(mContext, "取证成功！");
        sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
        Intent intent = new Intent(mContext, NpSpotListActivity.class);
        startActivity(intent);
        finish();
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @OnClick({
      R.id.ll_back, R.id.ll_right, R.id.ll_scan, R.id.iv_photo, R.id.tv_button
  }) public void onViewClicked(View view) {
    Intent intent;
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_photo:
      case R.id.ll_scan:
        picOne();
        break;
      case R.id.tv_button:
        plateNumber = gpvPlateNumber.getPassWord();
        if (!StringUtils.isBlank(plateNumber)) {
          if (!StringUtils.isBlank(carPath)) {
            showCommitDialog();
          } else {
            if (!StringUtils.isBlank(pic)) {
              showCommitDialog();
            } else {
              ToastUtil.showMessage(mContext, "请上传图片");
            }
          }
        } else {
          ToastUtil.showMessage(mContext, "请输入车牌号");
        }
        break;
    }
  }

  private void showCommitDialog() {
    CommonDialog.showYesOrNoWithTitleDialog(mContext, "", "确认提交", "取消", "确认", () -> {
      if (!StringUtils.isBlank(carPath)) {
        //上传图片后
        uploadPic();
      } else {
        updateNodeRecordPic();
      }
    }, () -> {

    });
  }
}
